"""

"""

from kivymd.uix.screen import MDScreen
from kivymd.uix.boxlayout import MDBoxLayout
from kivymd.uix.scrollview import MDScrollView
from kivymd.uix.card import MDCard
from kivymd.uix.label import MDLabel
from kivymd.uix.button import MDRaisedButton, MDFlatButton
from kivymd.uix.toolbar import MDTopAppBar
from kivymd.uix.selectioncontrol import MDSwitch
from kivymd.uix.menu import MDDropdownMenu
from kivymd.app import MDApp
from kivymd.toast import toast
from src.core.ollama_client import OllamaClient

class SettingsScreen(MDScreen):
    """"""
    
    whisper_options = ['tiny', 'base', 'small', 'medium', 'large']
    ollama_options = ['qwen2:1.5b', 'qwen2:7b', 'llama3.1:8b', 'llama3.2:3b']
    language_options = {'auto': '', 'zh': '', 'en': ''}
    style_options = {'concise': '', 'detailed': '', 'bullet_points': ''}

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self._build_ui()
        self._init_menus()

    def on_enter(self):
        """UI"""
        app = MDApp.get_running_app()
        self._update_ui_from_settings(app.settings_data)

    def _build_ui(self):
        main_layout = MDBoxLayout(orientation='vertical', spacing="10dp")
        toolbar = MDTopAppBar(title="", left_action_items=[["arrow-left", lambda x: self._go_back()]], right_action_items=[["content-save", lambda x: self._save_settings()]])
        main_layout.add_widget(toolbar)
        scroll = MDScrollView()
        content = MDBoxLayout(orientation='vertical', spacing="20dp", padding="20dp", adaptive_height=True)
        content.add_widget(self._create_ai_settings_card())
        content.add_widget(self._create_processing_settings_card())
        content.add_widget(self._create_app_settings_card())
        scroll.add_widget(content)
        main_layout.add_widget(scroll)
        button_layout = MDBoxLayout(orientation='horizontal', spacing="15dp", padding="20dp", size_hint_y=None, height="70dp")
        reset_btn = MDFlatButton(text=" ", size_hint_x=0.5)
        reset_btn.bind(on_press=self._reset_settings)
        button_layout.add_widget(reset_btn)
        save_btn = MDRaisedButton(text=" ", size_hint_x=0.5, md_bg_color=self.theme_cls.primary_color)
        save_btn.bind(on_press=self._save_settings)
        button_layout.add_widget(save_btn)
        main_layout.add_widget(button_layout)
        self.add_widget(main_layout)

    def _init_menus(self):
        """"""
        self.whisper_menu = self._create_dropdown_menu(self.whisper_btn, self.whisper_options, self._set_whisper_model)
        # 动态检测 Ollama 模型
        names, detected = self._get_ollama_options()
        self.ollama_options = names
        self.ollama_menu = self._create_dropdown_menu(self.ollama_btn, self.ollama_options, self._set_ollama_model)
        if not detected:
            self.ollama_btn.disabled = True
            self.ollama_btn.text = ""
        self.language_menu = self._create_dropdown_menu(self.language_btn, list(self.language_options.keys()), self._set_language, display_map=self.language_options)
        self.style_menu = self._create_dropdown_menu(self.style_btn, list(self.style_options.keys()), self._set_style, display_map=self.style_options)

    def _create_dropdown_menu(self, caller, items, callback, display_map=None):
        menu_items = [
            {
                "text": display_map.get(i, i) if display_map else i,
                "viewclass": "OneLineListItem",
                "on_release": lambda x=i: callback(x),
            } for i in items
        ]
        return MDDropdownMenu(caller=caller, items=menu_items, width_mult=4)

    def _set_whisper_model(self, model_name):
        self.whisper_btn.text = model_name
        self.whisper_menu.dismiss()

    def _set_ollama_model(self, model_name):
        self.ollama_btn.text = model_name
        self.ollama_menu.dismiss()

    def _set_language(self, lang_code):
        self.language_btn.text = self.language_options.get(lang_code, lang_code)
        self.language_menu.dismiss()

    def _set_style(self, style_key):
        self.style_btn.text = self.style_options.get(style_key, style_key)
        self.style_menu.dismiss()

    def _create_ai_settings_card(self):
        card = MDCard(orientation='vertical', padding="20dp", spacing="15dp", size_hint_y=None, adaptive_height=True, elevation=2)
        card.add_widget(MDLabel(text=" AI", theme_text_color="Primary", font_style="H6", size_hint_y=None, height="40dp"))
        
        self.whisper_btn = self._create_setting_row(card, "Whisper:")
        self.ollama_btn = self._create_setting_row(card, "Ollama:")
        self.language_btn = self._create_setting_row(card, ":")
        self.style_btn = self._create_setting_row(card, ":")
        return card

    def _create_setting_row(self, card, text):
        layout = MDBoxLayout(orientation='horizontal', spacing="10dp", size_hint_y=None, height="40dp")
        layout.add_widget(MDLabel(text=text, theme_text_color="Secondary", font_style="Body1", size_hint_x=0.4))
        button = MDRaisedButton(text="...", size_hint_x=0.6)
        button.bind(on_release=lambda x, b=button: self._open_menu_for_button(b))
        layout.add_widget(button)
        card.add_widget(layout)
        return button

    def _open_menu_for_button(self, button):
        if button == self.whisper_btn: self.whisper_menu.open()
        elif button == self.ollama_btn:
            if not getattr(self.ollama_btn, 'disabled', False):
                self.ollama_menu.open()
            else:
                toast("Ollama")
        elif button == self.language_btn: self.language_menu.open()
        elif button == self.style_btn: self.style_menu.open()

    def _create_processing_settings_card(self):
        card = MDCard(orientation='vertical', padding="20dp", spacing="15dp", size_hint_y=None, adaptive_height=True, elevation=2)
        card.add_widget(MDLabel(text=" ", theme_text_color="Primary", font_style="H6", size_hint_y=None, height="40dp"))
        self.gpu_switch = self._create_switch_row(card, "GPU:")
        self.cleanup_switch = self._create_switch_row(card, ":")
        return card

    def _create_app_settings_card(self):
        card = MDCard(orientation='vertical', padding="20dp", spacing="15dp", size_hint_y=None, adaptive_height=True, elevation=2)
        card.add_widget(MDLabel(text=" ", theme_text_color="Primary", font_style="H6", size_hint_y=None, height="40dp"))
        self.theme_switch = self._create_switch_row(card, ":")
        self.theme_switch.bind(active=self._toggle_theme)
        return card

    def _create_switch_row(self, card, text):
        layout = MDBoxLayout(orientation='horizontal', spacing="10dp", size_hint_y=None, height="40dp")
        layout.add_widget(MDLabel(text=text, theme_text_color="Secondary", font_style="Body1", size_hint_x=0.7))
        switch = MDSwitch(size_hint_x=0.3)
        layout.add_widget(switch)
        card.add_widget(layout)
        return switch

    def _toggle_theme(self, instance, active):
        app = MDApp.get_running_app()
        app.theme_cls.theme_style = "Dark" if active else "Light"

    def _save_settings(self, instance=None):
        app = MDApp.get_running_app()
        lang_code = next((k for k, v in self.language_options.items() if v == self.language_btn.text), 'auto')
        style_key = next((k for k, v in self.style_options.items() if v == self.style_btn.text), 'detailed')

        app.settings_data['whisper_model'] = self.whisper_btn.text
        app.settings_data['ollama_model'] = self.ollama_btn.text
        app.settings_data['language'] = lang_code
        app.settings_data['summary_style'] = style_key
        app.settings_data['device'] = 'cuda' if self.gpu_switch.active else 'cpu'
        app.settings_data['auto_cleanup'] = self.cleanup_switch.active
        
        toast("")
        self._go_back()

    def _reset_settings(self, instance):
        app = MDApp.get_running_app()
        default_settings = app._load_default_settings()
        self._update_ui_from_settings(default_settings)
        self._save_settings()
        toast("")

    def _update_ui_from_settings(self, settings):
        self.whisper_btn.text = settings.get('whisper_model', 'base')
        self.ollama_btn.text = settings.get('ollama_model', 'qwen2:7b')
        self.language_btn.text = self.language_options.get(settings.get('language', 'auto'), '')
        self.style_btn.text = self.style_options.get(settings.get('summary_style', 'detailed'), '')
        self.gpu_switch.active = settings.get('device', 'auto') == 'cuda'
        self.cleanup_switch.active = settings.get('auto_cleanup', True)
        self.theme_switch.active = MDApp.get_running_app().theme_cls.theme_style == "Dark"

    def _get_ollama_options(self):
        """从本地 Ollama 检测模型列表，不做预设回退"""
        try:
            app = MDApp.get_running_app()
            host = app.settings_data.get('ollama_host', 'localhost')
            port = app.settings_data.get('ollama_port', 11434)
            client = OllamaClient(base_url=f"http://{host}:{port}")
            models = client.list_models()
            names = [m.get('name') for m in models if m.get('name')]
            if names:
                return names, True
        except Exception:
            pass
        return [], False

    def _go_back(self):
        MDApp.get_running_app().navigate_to('main')
